﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using Oracle.ManagedDataAccess.Client;
using WFL.Data;
using WFL.Data.Oracle;
using WFL.Data.SqlClient;
using WFL.Utils;
using WFL.Threading;

namespace WFL.Demo.WinForm
{
    public partial class TestForm : Form
    {
        private BatchRuntime _batchRumtime;


        public TestForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                //Emiter emiter = new Emiter(new AssemblyName("ClassRiver"));
                //Type type = emiter.BuildTypes();
                //object result = type.GetMethod("Hello").Invoke(Activator.CreateInstance(type), new[] { "wjd" });

                //_batchRumtime = new BatchRuntime("MyRuntime", 10, null);
                _batchRumtime = new BatchRuntime(AppDomain.CurrentDomain.BaseDirectory + @"Threading\Batches.config", "batchRuntimes", "MyRuntime");
                _batchRumtime.Log += _batchRumtime_Log;
                _batchRumtime.Open();
            }
            catch (Exception ex)
            { 
            
            }
        }

        private void _batchRumtime_Log(object sender, LogEventArgs e)
        {
            string text = e.Text;
            if (e.Exception != null)
            {
                text = string.Format("Exception：{0}\r\nMessage：{1}\r\nStackTrace：{2}"
                    , e.Exception.GetType().FullName
                    , e.Exception.Message
                    , e.Exception.StackTrace);
                if (e.Exception.InnerException != null)
                {
                    text += string.Format("\r\nInnerException：{0}\r\nMessage：{1}\r\nStackTrace：{2}"
                        , e.Exception.InnerException.GetType().FullName
                        , e.Exception.InnerException.Message
                        , e.Exception.InnerException.StackTrace);
                }
            }
            BatchRuntime runtime = (BatchRuntime)sender;
            string logPath = AppDomain.CurrentDomain.BaseDirectory + @"BatchRuntime\" + runtime.Name + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            File.AppendAllText(logPath
                    , string.Format("\r\n----------------------------------------------------\r\n{0}：\r\n    {1}", DateTime.Now.ToString(), text));
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (_batchRumtime != null)
            {
                _batchRumtime.Close();
                _batchRumtime.Log -= _batchRumtime_Log;
                _batchRumtime = null;
            }
        }

        private void _pyConvert_Click(object sender, EventArgs e)
        {

        }

        private void _whatever_Click(object sender, EventArgs e)
        {
            #region Word测试

            //string docFile = AppDomain.CurrentDomain.BaseDirectory + @"test.doc";
            //WordApplication app = new WordApplication();
            //try
            //{
            //    WordDocument doc = app.Documents.Open(docFile);
            //    //WordRange range = doc.Range(0, 3);
            //    //string text="测试批注，啦啦啦";
            //    //doc.Comments.Add(range, text);
            //    //int count = doc.Paragraphs.Count;
            //    //WordParagraph p1 = doc.Paragraphs[1];
            //    //for (int i = 1; i < 100; i++)
            //    //{
            //    //    WordParagraph p2 = p1.Next();
            //    //    if (p2 == null)
            //    //    {
            //    //        MessageBox.Show(p1.Range.Text);
            //    //        break;
            //    //    }
            //    //    else
            //    //    {
            //    //        p1 = p2;
            //    //    }
            //    //}

            //    WordRange range = doc.Paragraphs[2].Range;
            //    int count = range.InlineShapes.Count;
            //    if (count > 0)
            //    {
            //        WordInlineShape shape = null;
            //        for (int i = 1; i <= count; i++)
            //        {
            //            shape = range.InlineShapes[i];
            //            MessageBox.Show("start:" + (shape.Range.Start-range.Start).ToString() + " end:" + shape.Range.End.ToString());
            //        }
            //    }

            //    //WordRange range = doc.Range(12, 13);
            //    //byte[] buffer = range.EnhMetaFileBits;
            //    //File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + @"2003raw.png", buffer);
            //    //MemoryStream stream = new MemoryStream(buffer);
            //    //try
            //    //{
            //    //    Bitmap image = new Bitmap(stream);
            //    //    image.Save(AppDomain.CurrentDomain.BaseDirectory + @"2003.png", System.Drawing.Imaging.ImageFormat.Png);
            //    //    image.Dispose();
            //    //}
            //    //finally
            //    //{
            //    //    stream.Close();
            //    //}

            //    doc.Save();
            //    doc.Close();
            //}
            //finally
            //{
            //    app.Dispose();
            //}

            #endregion


            //OracleORM orm = new OracleORM("Data Source=193.100.100.26:1522/Lic2.FGI;User ID=sirccat;Password=catcat;");
            //ExceptionLog entity = new ExceptionLog()
            //{
            //    HappenTime = DateTime.Now,
            //    Type = "Custom",
            //    Title = "测试NCLOB",
            //    Detail = File.ReadAllText(@"D:\Temp\Period2\error.txt", Encoding.Default),
            //    Operator = "WFL",
            //    OrganizationId = 1
            //};
            //try
            //{
            //    orm.Insert<ExceptionLog>(entity, "ExceptionLog", new string[] { "Type", "Title", "Detail", "HappenTime", "Operator", "OrganizationId" });
            //}
            //catch (Exception ex)
            //{

            //}
            //string buffer = File.ReadAllText(@"D:\Temp\Period2\error.txt", Encoding.Default);
            //ExceptionLog entity = orm.Select<ExceptionLog>(285581);

            try
            {
                _batchRumtime.Register(typeof(TestBatch1), "TestBatch1");
                BatchInstance instance = _batchRumtime.CreateInstance("TestBatch1");
                instance.Execute("我是执行数据：" + DateTime.Now.ToString());
                //for (int i = 0; i < 30; i++)
                //{
                //    _batchRumtime.Register(typeof(TestTimingBatch1)
                //        , "TestTimingBatch" + i.ToString()
                //        , new DateTime(2017, 01, 04, 8, 20, 0)
                //        , TimeSpan.FromMinutes(5));
                //}
            }
            catch (Exception ex)
            {

            }
        }

        private void _match_Click(object sender, EventArgs e)
        {
            string input = _input.Text;
            string pattern = _pattern.Text;
            try
            {
                MatchCollection matchCol = Regex.Matches(input, pattern);
                foreach (Match match in matchCol)
                {
                    foreach (Capture capture in match.Captures)
                    {
                        MessageBox.Show(capture.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            { 
            
            }
        }

        private void _doReplace_Click(object sender, EventArgs e)
        {
            try
            {
                string input = _input.Text;
                string pattern = _pattern.Text;
                string replacement = _replacement.Text;
                //string input = "select count(*) from [LicenseData]";
                //string pattern = @"((?<=(\s+from\s+)|(\s+join\s+))(?<table>\[?{0}\]?))|((?<table>\[?{0}\]?)(?=\.))";
                //pattern = string.Format(pattern, "[LicenseData]");
                //string replacement = "FSAQXKZ";
                MessageBox.Show(Regex.Replace(input, pattern, replacement,RegexOptions.IgnoreCase));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            { 
            
            }
        }
    }
}
